import {
  getRelateVideo
} from "@/api/video";
import {
  getDictByCode
} from "@/api/dic";
import globalVariable from "@/api/global_variable.js";

var SIGN_REGEXP = /([yMdhsm])(\1*)/g;
var DEFAULT_PATTERN = "yyyy-MM-dd";

//针对pc端业务数组处理
var ilinkArrHandle = {
  //七牛上传图片对象数组 =fn=>图片url数组
  getqiniuPicUrlArr: function (fileList) {
    let newArr = [];
    $.each(fileList, (index, obj) => {
      newArr.push(obj.response ? QINIUUPLOADURL.indexOf('uploadFile')>-1? obj.response.data:QINIUPATH + obj.response.key : obj.url);
    });
    return newArr;
  },
  //[{attr:av,attr1:2},{attr:av,attr1:2}] =fn=> [av,av]
  getArrObjAttrToArr: function (arr, attrName) {
    if (arr && Array.isArray(arr) && arr.length > 0) {
      let newArr = [];
      $.each(arr, (index, obj) => {
        newArr.push(obj[attrName]);
      });
      return newArr;
    } else {
      return [];
    }
  },
  //键值字典数组处理
  delDicArr_keyVal: function (code, cb) {
    var arr = [];
    getDictByCode({
      code: code
    }).then(data => {
      $.each(data.data.dictValueObj, (index, obj) => {
        arr.push(JSON.parse(obj.dictValue));
      });
      if (cb) cb(arr);
    });
  }
};
//针对pc端业务时间处理
var ilinkTimeformat = {
  //格式化时间成指定的格式； param{new date , string format}
  format: function (date, pattern) {
    pattern = pattern || DEFAULT_PATTERN;
    return pattern.replace(SIGN_REGEXP, function ($0) {
      switch ($0.charAt(0)) {
        case "y":
          return padding(date.getFullYear(), $0.length);
        case "M":
          return padding(date.getMonth() + 1, $0.length);
        case "d":
          return padding(date.getDate(), $0.length);
        case "w":
          return date.getDay() + 1;
        case "h":
          return padding(date.getHours(), $0.length);
        case "m":
          return padding(date.getMinutes(), $0.length);
        case "s":
          return padding(date.getSeconds(), $0.length);
      }
    });
  },
  parse: function (dateString, pattern) {
    var matchs1 = pattern.match(SIGN_REGEXP);
    var matchs2 = dateString.match(/(\d)+/g);
    if (matchs1.length == matchs2.length) {
      var _date = new Date(1970, 0, 1);
      for (var i = 0; i < matchs1.length; i++) {
        var _int = parseInt(matchs2[i]);
        var sign = matchs1[i];
        switch (sign.charAt(0)) {
          case "y":
            _date.setFullYear(_int);
            break;
          case "M":
            _date.setMonth(_int - 1);
            break;
          case "d":
            _date.setDate(_int);
            break;
          case "h":
            _date.setHours(_int);
            break;
          case "m":
            _date.setMinutes(_int);
            break;
          case "s":
            _date.setSeconds(_int);
            break;
        }
      }
      return _date;
    }
    return null;
  },
  //多少个小时前的时间； param{ int hours, string format}
  hoursAgo: function (hours, pattern) {
    return this.format(
      new Date(new Date().getTime() - 3600 * 1000 * parseInt(hours)),
      pattern
    );
  }
};

// 打开呼叫中心
function openCallCenter(orgId, name, type, row) {
  window.openCallCenter &&
    window.openCallCenter({
      name: name,
      orgId: orgId,
      type: type,
      row
    });
}

// 模拟量统计
function initViewsCharts($echarts, data, chartId, formAlarm) {
  //formAlarm : 函数调取方为实时警情，数据结构有差异
  if (!data || data.length < 1) {
    return;
  }
  var objchart = [];
  if (formAlarm) {
    for (var i = 0; i < data.length; i++) {
      objchart.push({
        dataTypeId: data[i].dataTypeId,
        analogUnits: data[i].detail.length > 0 ? data[i].detail[0].analogUnits : "",
        rows: data[i].detail,
        thresholdMax: data[i].thresholdMax,
        thresholdMin: data[i].thresholdMin
      });
    }
  } else {
    // objchart 来存放当前请求到的数据中各类图表和数据，可根据 objchart 的长度来判断几种
    for (var i = 0; i < data.length; i++) {
      // 默认没有找到该类型模拟量图表
      var hasTypeFlag = false;
      for (var j = 0; j < objchart.length; j++) {
        if (objchart[j].dataTypeId == data[i].dataTypeId) {
          // 添加某个图表中的一坐标
          objchart[j].rows.push({
            x: data[i].createTime,
            y: data[i].analogValue
          });
          hasTypeFlag = true;
          continue;
        }
      }
      // 没有找到对应类型图表，新绘制图表
      if (!hasTypeFlag) {
        var _subObj = {
          dataTypeId: data[i].dataTypeId,
          analogUnits: data[i].analogUnits,
          rows: [{
            x: data[i].createTime,
            y: data[i].analogValue
          }]
        };
        // 添加到图表类型集合中
        objchart.push(_subObj);
      }
    }
  }
  //把objchart重新排序，设备电压放最后
  if (objchart.length > 1) {
    for (var i = 0; i < objchart.length; i++) {
      if (objchart[i].dataTypeId == "3") {
        objchart.push(objchart[i]);
        objchart.splice(i, 1);
        break;
      }
    }
  }
  for (let i = 0; i < objchart.length; i++) {
    if (objchart[i].rows.length > 0) {
      let unit = objchart[i].analogUnits;
      let dataList = objchart[i].rows;
      let thresholdMin = objchart[i].thresholdMin || 0;
      let thresholdMax = objchart[i].thresholdMax || 0;
      let maxLeavel = 1;
      let minLeavel = 0;
      let superiorLowerLimit = []
      if ((thresholdMax == 0 || !thresholdMax) && (thresholdMin == 0 || !thresholdMin)) {
        superiorLowerLimit = []
      } else if (thresholdMin == 0 || !thresholdMin) {
        superiorLowerLimit = [{
          name: "上限值",
          yAxis: thresholdMax
        }]
      } else if (thresholdMax == 0 || !thresholdMax) {
        superiorLowerLimit = [{
          name: "下限值",
          yAxis: thresholdMin
        }]
      } else {
        superiorLowerLimit = [{
            name: "下限值",
            yAxis: thresholdMin
          },
          {
            name: "上限值",
            yAxis: thresholdMax
          }
        ]
      }
      if (formAlarm) {
        maxLeavel = Math.max.apply(
          null,
          dataList.map(function (v) {
            return v.analogValue;
          })
        );
        minLeavel = Math.min.apply(
          null,
          dataList.map(function (v) {
            return v.analogValue;
          })
        );
      } else {
        maxLeavel = Math.max.apply(
          null,
          dataList.map(function (v) {
            return v.y;
          })
        );
        minLeavel = Math.min.apply(
          null,
          dataList.map(function (v) {
            return v.y;
          })
        );
      }
      let xInterval = 3;
      let xArr = [];
      let xArr_haveYear = {};
      let yArr = [];
      if (formAlarm) {
        $.each(dataList, function (index, obj) {
          xArr.push(ilinkTimeformat.format(new Date(obj.datetime), "hh:mm:ss"));
          xArr_haveYear[index] = ilinkTimeformat.format(
            new Date(obj.datetime),
            "yyyy-MM-dd hh:mm:ss"
          );
          yArr.push(obj.analogValue);
        });
      } else {
        $.each(dataList, function (index, obj) {
          xArr.push(ilinkTimeformat.format(new Date(obj.x), "hh:mm:ss"));
          xArr_haveYear[index] = ilinkTimeformat.format(
            new Date(obj.x),
            "yyyy-MM-dd hh:mm:ss"
          );
          yArr.push(obj.y);
        });
      }
      let option_echart = {
        title: {
          text: "",
          left: 20,
          textStyle: {
            color: "#999",
            fontSize: "16px",
            align: "center"
          },
          subtext: ""
        },
        grid: {
          height: "80%",
          right: 150,
          left: 50,
          bottom: 35,
          borderWidth: 1,
          top: 15
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "rgba(0,0,0,0.8)"
            }
          },
          formatter: function (params) {
            var _score = params[0].value;
            return (
              xArr_haveYear[params[0].dataIndex] +
              "<br/>" +
              (_score ? _score + unit : "0" + unit)
            );
          }
        },
        toolbox: {
          show: false
        },
        xAxis: {
          type: "category",
          axisTick: {
            show: false
          },
          triggerEvent: true,
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(225, 225, 225,0.8)",
              width: 1 //这里是为了突出显示加上的
            }
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: "#999999",
              fontSize: 14
            }
            //interval:xInterval
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: ["rgba(225, 225, 225,0.8)"],
              opacity: 0.7
            }
          },
          //max:30,
          boundaryGap: false,
          data: xArr
        },
        yAxis: {
          type: "value",
          axisTick: {
            show: false
          },
          /*min:minLeavel,
          max:maxLeavel,*/
          axisLine: {
            show: true,
            lineStyle: {
              color: "rgba(225, 225, 225,0.8)",
              width: 1 //这里是为了突出显示加上的
            }
          },
          axisLabel: {
            formatter: "{value}",
            show: true,
            textStyle: {
              color: "#999999",
              fontSize: 14
            }
          },
          splitLine: {
            lineStyle: {
              color: ["rgba(225, 225, 225,0.8)"],
              opacity: 0.7
            }
          },
          axisPointer: {
            snap: true
          }
        },
        series: [{
          name: "模拟量",
          type: "line",
          smooth: true,
          //areaStyle: { normal: {} },
          symbolSize: 11,
          itemStyle: {
            normal: {
              color: "#5c90d2",
              lineStyle: {
                color: "#5c90d2",
                width: 3
              }
            }
          },
          markLine: {
            itemStyle: {
              normal: {
                lineStyle: {
                  type: "dashed",
                  color: "red"
                },
                label: {
                  show: true,
                  position: "end", //'start' 线的起始点。'middle' 线的中点。'end' 线的结束点。
                  formatter: function (param) {
                    return param.name + param.value;
                  },
                  textStyle: {
                    fontSize: 16
                  }
                }
              }
            },
            //symbolSize:0,
            silent: true,
            data: superiorLowerLimit
          },
          data: yArr
        }]
      };
      if (option_echart && typeof option_echart === "object") {
        var $dom = document.getElementById(
          chartId + "-" + objchart[i].dataTypeId
        );
        if ($dom) $echarts.init($dom).setOption(option_echart, true);
      }
    }
  }
}
// 非模拟量统计
function initViewsCharts_noAnalog($echarts, timeArr, alertType, chartId) {
  let xArr = [];
  let yArr = [];
  let colorBox = {
    10: "rgba(253,94,94,1)",
    20: "rgba(255,196,64,1)",
    30: "rgba(136,144,171,1)",
    40: "rgba(76,164,254,1)"
  };
  let yTitleBox = {
    10: "报警",
    20: "故障",
    30: "屏蔽",
    40: "联动"
  };
  let alertTitle = yTitleBox[alertType];
  let color1 = colorBox[alertType];
  $.each(timeArr, function (index, _time) {
    xArr.push(
      ilinkTimeformat.format(
        _time ? new Date(_time) : new Date(),
        "yyyy-MM-dd hh:mm:ss"
      )
    );
    yArr.push(alertType);
  });
  let option_echart = {
    title: {
      text: "",
      left: 20,
      textStyle: {
        color: "#999",
        fontSize: "16px",
        align: "center"
      },
      subtext: ""
    },
    grid: {
      width: "92%",
      height: "80%",
      right: 0,
      left: 50,
      bottom: 35,
      borderWidth: 1,
      top: 15
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        label: {
          backgroundColor: "rgba(0,0,0,0.8)"
        }
      },
      formatter: function (params) {
        return xArr[params[0].dataIndex] + "<br/>" + alertTitle;
      }
    },
    toolbox: {
      show: false
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      triggerEvent: true,
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(225, 225, 225,0.8)",
          width: 1 //这里是为了突出显示加上的
        }
      },
      axisLabel: {
        show: true,
        textStyle: {
          color: "#999999",
          fontSize: 14
        }
        //interval:xInterval
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: ["rgba(225, 225, 225,0.8)"],
          opacity: 0.7
        }
      },
      //max:30,
      boundaryGap: false,
      data: xArr
    },
    yAxis: {
      type: "value",
      axisTick: {
        show: false
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "rgba(225, 225, 225,0.8)",
          width: 1 //这里是为了突出显示加上的
        }
      },
      axisLabel: {
        formatter: function (e) {
          return yTitleBox[e] || "";
        },
        show: true,
        textStyle: {
          color: "#999999",
          fontSize: 14
        }
      },
      interval: alertType,
      splitLine: {
        lineStyle: {
          color: ["rgba(225, 225, 225,0.8)"],
          opacity: 0.7
        }
      },
      axisPointer: {
        snap: true
      }
    },
    series: [{
      name: "报警类型",
      type: "line",
      smooth: true,
      areaStyle: {
        normal: {}
      },
      symbolSize: 11,
      itemStyle: {
        normal: {
          color: color1,
          lineStyle: {
            color: color1,
            width: 3
          }
        }
      },
      data: yArr
    }]
  };
  if (option_echart && typeof option_echart === "object") {
    var $dom = document.getElementById(chartId);
    if ($dom) $echarts.init($dom).setOption(option_echart, true);
  }
}
//时间筛选组对象定义
/*
forwardOrFuture : 默认false '过去'，true '将来'
 */
function intTimePickerOptions(forwardOrFuture) {
  return {
    shortcuts: [{
        text: (forwardOrFuture ? "将来" : "过去") + "一周",
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          if (forwardOrFuture) {
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
          } else {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          }
          picker.$emit("pick", [start, end]);
        }
      },
      {
        text: (forwardOrFuture ? "将来" : "过去") + "一个月",
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          if (forwardOrFuture) {
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
          } else {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          }
          picker.$emit("pick", [start, end]);
        }
      },
      {
        text: (forwardOrFuture ? "将来" : "过去") + "三个月",
        onClick(picker) {
          const end = new Date();
          const start = new Date();
          if (forwardOrFuture) {
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
          } else {
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          }
          picker.$emit("pick", [start, end]);
        }
      }
    ]
  };
}
//时间筛选组对象定义
/*
forwardOrFuture : 默认false '过去'，true '将来'
 */
function intDatePickerOptions(forwardOrFuture) {
  return {
    /*disabledDate(time) {
            return time.getTime() > Date.now();
          },*/
    shortcuts: [{
        text: "今天",
        onClick(picker) {
          picker.$emit("pick", new Date());
        }
      },
      {
        text: forwardOrFuture ? "明天" : "昨天",
        onClick(picker) {
          const date = new Date();
          if (forwardOrFuture) {
            date.setTime(date.getTime() + 3600 * 1000 * 24);
          } else {
            date.setTime(date.getTime() - 3600 * 1000 * 24);
          }
          picker.$emit("pick", date);
        }
      },
      {
        text: forwardOrFuture ? "一周后" : "一周前",
        onClick(picker) {
          const date = new Date();
          if (forwardOrFuture) {
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
          } else {
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
          }
          picker.$emit("pick", date);
        }
      }
    ]
  };
}
//富文本编辑器组对象定义
function intEditorOptions(readOnly) {
  return {
    theme: "snow",
    boundary: document.body,
    modules: {
      toolbar: [
        ["bold", "italic", "underline", "strike"],
        ["blockquote", "code-block"],
        [{
          header: 1
        }, {
          header: 2
        }],
        [{
          list: "ordered"
        }, {
          list: "bullet"
        }],
        [{
          script: "sub"
        }, {
          script: "super"
        }],
        [{
          indent: "-1"
        }, {
          indent: "+1"
        }],
        [{
          direction: "rtl"
        }],
        [{
          size: ["small", false, "large", "huge"]
        }],
        [{
          header: [1, 2, 3, 4, 5, 6, false]
        }],
        [{
          color: []
        }, {
          background: []
        }],
        [{
          font: []
        }],
        [{
          align: []
        }],
        ["clean"],
        ["link", "image", "video"]
      ]
    },
    placeholder: "输入内容 ...",
    readOnly: readOnly ? true : false
  };
}
//报警类型
function transFireTypeTagType(type) {
  let type1 = type.toString();
  let typeName = "";
  let colorType = "";
  if (type1.indexOf("10") > -1) {
    colorType = "bg-color-1";
    typeName = "报警";
  } else if (type1.indexOf("20") > -1) {
    colorType = "bg-color-2";
    typeName = "故障";
  } else if (type1.indexOf("30") > -1) {
    colorType = "bg-color-8";
    typeName = "屏蔽";
  } else if (type1.indexOf("40") > -1) {
    colorType = "bg-color-4";
    typeName = "联动";
  } else {
    colorType = "bg-color-3";
    typeName = "正常";
  }
  return `<div class="type-tags ` + colorType + `">` + typeName + `</div>`;
}
//处理进度
function transhandlerStatusText(type) {
  if (type == 1) {
    return "已处理";
  } else if (type == 2) {
    return "处理中";
  } else {
    return "未处理";
  }
}
//处理进度
function transhandlerStatusColor(type) {
  if (type == 1) {
    return "bg-color-3";
  } else if (type == 2) {
    return "bg-color-4";
  } else {
    return "bg-color-2";
  }
}
//处理进度
function transhandlerStatusPer(type) {
  if (type == 1) {
    return 100;
  } else if (type == 2) {
    return 50;
  } else {
    return 0;
  }
}
// tag处理进度
function transhandlerStatusTag(type) {
  if (type == 1) {
    return "success";
  } else if (type == 2) {
    return "info";
  } else {
    return "warning";
  }
}
//巡检结果
function transInspectResultTagType(type) {
  if (type == 1) {
    return "exception";
  } else {
    return "success";
  }
}
//巡检结果
function transInspectResultText(type) {
  if (type == 1) {
    return "未完成";
  } else {
    return "已完成";
  }
}
//巡检状态
function transInspectStatusTagType(type) {
  if (type == 1) {
    return "exception";
  } else {
    return "success";
  }
}
//巡检状态
function transInspectStatusText(type) {
  if (type == 1) {
    return "执行中";
  } else {
    return "已结束";
  }
}
//巡检点位状态
function transInspectPointStatusTagType(type) {
  if (type == 0) {
    return "exception";
  } else if (type == 1) {
    return "text";
  } else {
    return "success";
  }
}
//巡检点位状态
function transInspectPointStatusText(type) {
  if (type == 0) {
    return "待领取";
  } else if (type == 1) {
    return "执行中";
  } else if (type == 2) {
    return "巡检完成";
  }
}
//公告状态
function transNoticeTagType(type) {
  if (type == 0) {
    return "exception";
  } else if (type == 1) {
    return "text";
  } else {
    return "success";
  }
}
//公告状态
function transNoticeText(type) {
  if (type == 0) {
    return "未开始";
  } else if (type == 1) {
    return "公告中";
  } else if (type == 2) {
    return "已结束";
  }
}
//巡检计划状态
function transInspectPlanStatus(status) {
  return ['', '在用', '停用', '结束'][status || 0]
}
// tag巡检计划状态
function transInspectPlanStatusTag(status) {
  return ['', 'success', 'warning', 'primary'][status || 0]
}
// 安全评估分数获取颜色
function getColorByScore(score, getRgba) {
  let fixScore = parseFloat(parseFloat(score).toFixed(1));
  if (79.9 < fixScore && fixScore < 89.9) {
    //风险
    return getRgba ? "#FFB32D" : "yellow";
  } else if (fixScore < 80) {
    //高危
    return getRgba ? "#FD5E5E" : "red";
  } else {
    //安全
    return getRgba ? "#47CFAD" : "green";
  }
}

//身份证号码格式化
function transID(value) {
  if (value && value.length > 6) {
    return (
      value.substring(0, 3) + "************" + value.substring(value.length - 3)
    );
  }
  return "";
}

//维保任务完成度
//计算两个整数的百分比值  最多保留2位 isparseInt 表示取整
function completionDegree(num, total, isparseInt) {
  var num = parseFloat(num || 0);
  var total = parseFloat(total || 0);
  if (isNaN(num) || isNaN(total)) {
    return 0;
  }
  if (num > total) {
    return 100;
  }
  if (isparseInt) {
    return total <= 0 ? 0 : Math.round(num / total) * 100;
  } else {
    return total <= 0 ? 0 : Math.round((num * 100 * 100) / total) / 100;
  }
}

/*视频相关2*/
//绑定菜单视频点击事件
function menu_vedio_click() {
  var rdsp_vedio = getVedioUrl();
  showVedio(rdsp_vedio);
}

function getVedioUrl() {
  var rdsp_vedio = {
    cameraIds: [],
    organizationId: localStorage.getItem("ilink_platformCode_platId"),
    serverId: "",
    userName: JSON.parse(localStorage.getItem("userInfo")).accountName,
    orgPermissions: [],
    cameras: [],
    ver: ""
  };
  return rdsp_vedio;
}

function rowShowVedio(rowData, isCapScreen, videoItem) {
  if (!rowData.fcFacilitiesId) {
    topVue.$message.warning(`无关联视频信息`);
    return;
  }
  var rdsp_vedio = getVedioUrl();
  if (isCapScreen) {
    //视频截图
    rdsp_vedio["capScreenId"] = rowData.id;
    rdsp_vedio["capCreateTime"] = rowData.createTime;
  }
  rdsp_vedio["organizationId"] = rowData.organizationId;
  rdsp_vedio["serverId"] = rowData.serverId || "";
  rdsp_vedio["startTime"] = rowData.startTime || "";
  rdsp_vedio["endTime"] = rowData.endTime || "";
  getRelateVideo({
    relateObjType: 1, //关联对象类型 1: 消防设施 2:消防建筑物 3:资产
    relateObjId: rowData.fcFacilitiesId
  }).then(result => {
    let videoArr = result.data
    if (videoItem) {
      videoArr = videoArr.filter(n => {
        return n.deviceId == videoItem.deviceId
      })
    }
    var devicearray = [];
    $.each(videoArr, (index, obj) => {
      devicearray.push({
        authId: obj.authId,
        deviceId: obj.deviceId,
        type: obj.type,
        channel: obj.channel,
        organizationId: obj.organizationId
      });
    });
    rdsp_vedio["cameras"] = devicearray;
    showVedio(rdsp_vedio);
  });
}

/* 后台直接返回视频信息的 */
function defaultShowVideo(acceptData) {
  const rdsp_vedio = getVedioUrl();
  rdsp_vedio["organizationId"] = acceptData.organizationId;
  rdsp_vedio["serverId"] = acceptData.serverId || "";
  const devicearray = [];
  devicearray.push({
    authId: acceptData.authId,
    deviceId: acceptData.deviceId,
    type: acceptData.type,
    channel: acceptData.channel,
    organizationId: acceptData.organizationId
  });
  rdsp_vedio["cameras"] = devicearray;
  showVedio(rdsp_vedio);
}

function showVedio(vedioArr) {
  vedioArr.organizationId = localStorage.getItem("ilink_platformCode_platId");
  var vedioSetKey = CONFIGBOX[CONFIGKEY].videokey;
  var vedioUrl = JSON.stringify(vedioArr);
  let loginId =
    JSON.parse(localStorage.getItem("userInfo")).loginId || PLATCOEDEFAULT;
  if (loginId != PLATCOEDEFAULT) {
    vedioSetKey = vedioSetKey.split("-")[0] + "-" + loginId + "-vision:";
  }
  var url_new = vedioSetKey + encodeURI(vedioUrl.replace(/"/gm, "'"));
  if (window.external.openVedioClient == undefined) {
    window.location.href = url_new;
  } else {
    window.external.openVedioClient(url_new);
  }
}

function padding(s, len) {
  var len = len - (s + "").length;
  for (var i = 0; i < len; i++) {
    s = "0" + s;
  }
  return s;
}

/*维保任务模块*/
//维保任务状态
function transMaintenceStatus(type) {
  let typeName = "";
  let colorType = "";
  if (type == 1) {
    colorType = "bg-color-3";
    typeName = "未开始";
  } else if (type == 2) {
    colorType = "bg-color-4";
    typeName = "进行中";
  } else {
    colorType = "bg-color-8";
    typeName = "已结束";
  }
  return `<span class="tatus-icon-tags ` + colorType + `"></span>` + typeName;
}
/**
 * 后端非法数据格式化
 *
 */
//把后端传来的null或对象的undefined属性转为""
function transNullundefined(a) {
  if (a == null || a == undefined) {
    return "";
  } else {
    return a;
  }
}

function transNullundefinedToline(a) {
  if (a == null || a == undefined) {
    return "-";
  } else {
    return a;
  }
}

/**
 * 是否全屏并按键ESC键的方法
 */
function checkFull() {
  let isFull =
    /*parent.document.fullscreenEnabled || */
    top.window.fullScreen ||
    parent.document.webkitIsFullScreen ||
    parent.document.msFullscreenEnabled;
  //to fix : false || undefined == undefined
  if (isFull === undefined) isFull = false;
  return isFull;
}

/****************************************解决JS浮点数(小数)计算加减乘除的BUG    Start****************************************/

/**
 ** 加法函数，用来得到精确的加法结果
 ** 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
 ** 调用：accAdd(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
function accAdd(arg1, arg2) {
  if (isNaN(arg1)) {
    arg1 = 0;
  }
  if (isNaN(arg2)) {
    arg2 = 0;
  }
  arg1 = Number(arg1);
  arg2 = Number(arg2);
  var r1, r2, m, c;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  c = Math.abs(r1 - r2);
  m = Math.pow(10, Math.max(r1, r2));
  if (c > 0) {
    var cm = Math.pow(10, c);
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace(".", ""));
      arg2 = Number(arg2.toString().replace(".", "")) * cm;
    } else {
      arg1 = Number(arg1.toString().replace(".", "")) * cm;
      arg2 = Number(arg2.toString().replace(".", ""));
    }
  } else {
    arg1 = Number(arg1.toString().replace(".", ""));
    arg2 = Number(arg2.toString().replace(".", ""));
  }
  return (arg1 + arg2) / m;
}

//给Number类型增加一个add方法，调用起来更加方便。
/*Number.prototype.add = function(arg) {
    return accAdd(this, arg);
};*/

/**
 ** 减法函数，用来得到精确的减法结果
 ** 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
 ** 调用：accSub(arg1,arg2)
 ** 返回值：arg1加上arg2的精确结果
 **/
function accSub(arg1, arg2) {
  if (isNaN(arg1)) {
    arg1 = 0;
  }
  if (isNaN(arg2)) {
    arg2 = 0;
  }
  arg1 = Number(arg1);
  arg2 = Number(arg2);

  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
  n = r1 >= r2 ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

// 给Number类型增加一个mul方法，调用起来更加方便。
/*Number.prototype.sub = function(arg) {
    return accSub(this, arg);
};*/

/**
 ** 乘法函数，用来得到精确的乘法结果
 ** 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
 ** 调用：accMul(arg1,arg2)
 ** 返回值：arg1乘以 arg2的精确结果
 **/
function accMul(arg1, arg2) {
  if (isNaN(arg1)) {
    arg1 = 0;
  }
  if (isNaN(arg2)) {
    arg2 = 0;
  }
  arg1 = Number(arg1);
  arg2 = Number(arg2);

  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) {}
  try {
    m += s2.split(".")[1].length;
  } catch (e) {}
  return (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  );
}

// 给Number类型增加一个mul方法，调用起来更加方便。
/*Number.prototype.mul = function(arg) {
    return accMul(this, arg);
};
*/
/**
 ** 除法函数，用来得到精确的除法结果
 ** 说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
 ** 调用：accDiv(arg1,arg2)
 ** 返回值：arg1除以arg2的精确结果
 **/
function accDiv(arg1, arg2) {
  if (isNaN(arg1)) {
    arg1 = 0;
  }
  if (isNaN(arg2)) {
    arg2 = 0;
  }
  arg1 = Number(arg1);
  arg2 = Number(arg2);

  var t1 = 0,
    t2 = 0,
    r1,
    r2;
  try {
    t1 = arg1.toString().split(".")[1].length;
  } catch (e) {}
  try {
    t2 = arg2.toString().split(".")[1].length;
  } catch (e) {}
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
}

//给Number类型增加一个div方法，调用起来更加方便。
/*Number.prototype.div = function(arg) {
    return accDiv(this, arg);
};*/
/****************************************解决JS浮点数(小数)计算加减乘除的BUG  End****************************************/

function formatPicUrl(val) {
  if (val.indexOf('imageView2') > -1) return val
  if (val.indexOf('://file.kshqfire.com') < 0 && val.indexOf('://file.yx-ilink.com') < 0) return val + '?w=192&h=108'
  if (val.indexOf('imageView2') < 0) return val + '?imageView2/2/w/192/h/108/q/75'
  return val
}

function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], {
    type: mime
  })
}

function getTimeDuration(seconds) {
  let day = Math.floor(seconds / 86400)
  let hour = Math.floor((seconds - 86400 * day) / 3600)
  let minute = Math.floor((seconds - 86400 * day - hour * 3600) / 60)
  let sec = seconds - 86400 * day - hour * 3600 - minute * 60
  let valueArr = [{
    value: day,
    unit: '天'
  }, {
    value: hour,
    unit: '小时'
  }, {
    value: minute,
    unit: '分钟'
  }, {
    value: sec,
    unit: '秒'
  }]
  return valueArr.filter(n => {
    return n.value > 0
  })
}

export default {
  openCallCenter,
  ilinkTimeformat,
  ilinkArrHandle,
  initViewsCharts,
  initViewsCharts_noAnalog,
  transFireTypeTagType,
  transhandlerStatusText,
  transhandlerStatusColor,
  transhandlerStatusTag,
  transhandlerStatusPer,
  transInspectResultTagType,
  transInspectResultText,
  transInspectStatusTagType,
  transInspectStatusText,
  transInspectPointStatusTagType,
  transInspectPointStatusText,
  transInspectPlanStatus,
  transInspectPlanStatusTag,
  transID,
  menu_vedio_click,
  rowShowVedio,
  defaultShowVideo,
  transNullundefined,
  transNullundefinedToline,
  transMaintenceStatus,
  transNoticeTagType,
  transNoticeText,
  intDatePickerOptions,
  intTimePickerOptions,
  intEditorOptions,
  checkFull,
  completionDegree,
  getColorByScore,
  accAdd,
  accSub,
  accMul,
  accDiv,
  formatPicUrl,
  dataURLtoBlob,
  getTimeDuration
};
